package com.lyr.lock;

import java.util.concurrent.locks.ReentrantLock;

public class Bank {
    // 账户余额
    private int account=100;

   private final ReentrantLock lock = new ReentrantLock();

    // 方法：咨询
    public void ask(){

        this.lock.lock();

        try {
            System.out.println(Thread.currentThread().getName() + "正在咨询。。。");
            try {
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName() + "咨询结束。。。");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }finally {
            this.lock.unlock();
        }
    }

    // 方法:取钱
    public int getMoney(int order){

        this.lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在取款。。。");

            if (account >= order) {
                System.out.println("系统正在处理。。。");
                // Math 方法，产生随机数
                long m = (long) (Math.random() * 2000 + 600);
                try {
                    // 线程休眠时间
                    Thread.sleep(m);


                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 当前账户余额
                account -= order;
                // 当前操作对象的信息：返回对当前正在执行的线程对象的引用
                String name = Thread.currentThread().getName();

                System.out.println("尊敬的" + name + "用户,取款金额为："
                        + order + "元，账户余额为：" + account + "元");
                return order;
            } else {
                System.out.println("操作失败，您的余额不足。。。。");
                return 0;
            }
        }finally {
           this.lock.unlock();
        }

    }


}
